package org.lmind.example.common.web.spring;

import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletContext;

import org.apache.commons.collections.iterators.IteratorEnumeration;
import org.lmind.example.common.web.ApplicationContext;
import org.lmind.example.common.web.GeneralWebResourceResolver;
import org.lmind.example.common.web.ApplicationContextAttributeNames;
import org.lmind.example.common.web.UrlResolver;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;

public class SpringWebApplicationContext implements ApplicationContext, ServletContextAware, InitializingBean {
	
	private GeneralWebResourceResolver resourceResolver;
	
	private ServletContext servletContext;
	
	private HashMap<String, String> attributes = new HashMap<String, String>();

	@Override
	public UrlResolver getUrlResolver() {
		return resourceResolver;
	}

	public void setResourceResolver(GeneralWebResourceResolver resourceResolver) {
		this.resourceResolver = resourceResolver;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public Object getValue(String name) {
		return attributes.get(name);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Enumeration<String> getNames() {
		return new IteratorEnumeration(attributes.keySet().iterator());
	}
	
	private void setAttributes() {
		attributes.put(ApplicationContextAttributeNames.CONTEXT_PATH, servletContext.getContextPath());
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		servletContext.setAttribute(ApplicationContext.WEB_APP_CONTEXT_NAME, this);
		setAttributes();
	}
}
